#include "recbox.h"
#include "ui_recbox.h"

#include <recboxitem.h>
#include <QJsonObject>
RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(2),
    col(8)
{
    ui->setupUi(this);

}

void RecBox::initRecBoxUi(QJsonArray data, int row)
{
    if(row == 2)
    {
        this->row =row;
        this->col = 8;
    }
    else
    {
        ui->recListDown->hide();
    }

    imageList = data;

    // 默认显⽰第0组
     currentIndex = 0;

     // 计算总共有⼏组图⽚，ceil表⽰向上取整
     count = imageList.size()/col;

    // 往RecBox中添加图⽚
     createRecBoxItem();

}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::createRecBoxItem()
{

    QList<RecBoxItem*> recUpList = ui->recListUp->findChildren<RecBoxItem*>();
    for(auto e : recUpList)
    {
        ui->recListUpHLayout->removeWidget(e);
        delete e;
    }

    QList<RecBoxItem*> recDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for(auto e : recDownList)
    {
        ui->recListDownHLayout->removeWidget(e);
        delete e;
    }


    // 创建RecBoxItem对象，往RecBox中添加
     // col
     int index = 0;
     for(int i = currentIndex*col; i < col + currentIndex*col; ++i)
     {
         RecBoxItem* item = new RecBoxItem();
         // 设置⾳乐图⽚与对应⽂本
         QJsonObject obj = imageList[i].toObject();
         item->setText(obj.value("text").toString());
         item->setImage(obj.value("path").toString());

         // 将RecBoxItem对象添加到RecBox中
         if(index >= col/2 && row == 2)
         {
             ui->recListDownHLayout->addWidget(item);
         }
         else
         {
             ui->recListUpHLayout->addWidget(item);
         }

         ++index;
    }
}

void RecBox::on_btUp_clicked()
{
    currentIndex--;
    if(currentIndex < 0)
    {
        currentIndex = count - 1;
    }
    createRecBoxItem();
}


void RecBox::on_btDown_clicked()
{
    currentIndex++;
    if(currentIndex >= count)
    {
        currentIndex = 0;
    }
    createRecBoxItem();
}
